package com.ks.servlet;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ks.entity.User;
import com.ks.service.UserService;
import com.ks.utils.Factory;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static Log log = LogFactory.getLog(RegisterServlet.class);
	private static final long serialVersionUID = 1L;
	private static UserService userServiceImpl = (UserService) Factory.getBean("userServiceImpl");

	public RegisterServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		if (userServiceImpl.getUserById(username) != null) {
			request.getRequestDispatcher("/jsp/register.jsp").forward(request, response);
			return;
		}
		String password = request.getParameter("password");
		int age = 0;
		try {
			age = Integer.parseInt(request.getParameter("age"));
		} catch (Exception e) {
			log.error("传入年龄【" + request.getParameter("age") + "】错误！");
		}

		String address = request.getParameter("address");
		String[] hobbys = request.getParameterValues("hobby");
		String hobby = Arrays.toString(hobbys);

		String img = request.getParameter("img");
		User user = new User(username, password, age, hobby, address, img);
		int ret = userServiceImpl.insertOneUser(user);
		if (ret == 1) {
			response.sendRedirect("/jsp/login.jsp");
			log.info(username + "--用户注册成功！");
		} else {
			response.sendRedirect("/jsp/register.jsp");

		}
	}

}
